import {action, computed, observable, runInAction} from "mobx";
import {BaseResInterface, sendGetRequest, sendPostRequest} from "../../../net";
import {
    PageInterface, ProductCategoryRelation,
    ProductCommentInterface,
    ProductModelExtraInfoInterface,
    ProductModelInterface, ProductSpecificationInterface, UserModelInterface, UserProductRelationInterface
} from "../../../net/instance/CommenModelInstance";
import * as _ from "lodash";
import {realm} from "../../../dao";
import {
    defaultArr,
    defaultObj,
    excludeEmpty,
    getAssetUrl,
    getImageSizeRatio,
    isSameDate,
    PromiseWrapper
} from "../../../util";
import {screenWidth} from "../../../style";
import {Image} from "react-native";
import toast from "../../../component/common/ToastProxy";
import UserStoreInstance from "../user";
import {Collection} from "realm";

interface ProductResInterface<T> extends BaseResInterface {
    data: T
}

interface Product {
    count: number,
    rows: ProductModelInterface[]
}

interface ImageSize {
    width: number;
    height: number
}

export enum ActionTag {
    REFRESH, LOADMORE
};

export class ProductStore {
    @observable
    products: ProductModelInterface[] = [];
    @observable
    userProductRelation: UserProductRelationInterface = defaultObj;
    @observable
    count: number = 0;
    @observable
    productDetail: ProductModelExtraInfoInterface = defaultObj;
    @observable
    imageSize: ImageSize = defaultObj

    @observable
    productComments: ProductCommentInterface[] = defaultArr;

    @observable
    productSpecifications: ProductSpecificationInterface[] = defaultArr;

    @observable
    buyMaxCount: number = 0;

    dbProductStore: Collection<ProductModelInterface> = defaultArr;
    dbProductCategoryRelationStore: Collection<ProductCategoryRelation> = defaultArr;

    constructor() {
        this.dbProductStore = realm.objects<ProductModelInterface>("Product");
        this.dbProductCategoryRelationStore = realm.objects<ProductCategoryRelation>("ProductCategoryRelation");
    }

    isAlreadyInit = false;

    initialListValue(categoryId: number) {
        if (this.isAlreadyInit) return;
        const productCategoryRelations = this.dbProductCategoryRelationStore.filtered(`categoryId = ${categoryId}`);
        const productIds = productCategoryRelations.map(relation => relation.productId);
        //如果本地没有改分类的商品测直接取消初始化
        if (!productIds.length) return;
        const queryStr = productIds.reduce((initVal, id, index) => {
            const isLast = index == productIds.length - 1;
            return initVal + (isLast ? `${id}` : `${id} OR id = `);

        }, "id = ");
        this.products = _.toArray(this.dbProductStore.filtered(queryStr).sorted("id"));
        this.count = this.products.length;
        this.isAlreadyInit = true;
    }

    /***
     * 先本地化存储
     * 根据商品分类和页码获取当前tab的列表数据（商品）
     * @param action 刷新或者加载更多
     * @param categoryId
     * @param page
     */
    @action.bound
    getOrderListData = async (action: ActionTag, categoryId: number, page: PageInterface) => {
        this.initialListValue(categoryId);
        //获取到本次加载的数据
        const {data} = await sendGetRequest<ProductResInterface<Product>>("main/getProductsByPage", excludeEmpty({
            pageNum: page.pageNum,
            pageSize: page.pageSize,
            categoryId
        }));
        //将本次获取到的数据赋值给当前页面的列表
        let products = defaultArr;
        const rows = _.cloneDeep(data.rows);
        if (action === ActionTag.REFRESH) {
            products = rows;
        } else {
            products = this.products.concat(rows);
        }
        console.log(products);
        runInAction(() => {
            this.products = products;
            this.count = data.count;
        });
        realm.write(() => {
            rows.forEach((product) => {
                realm.create<ProductModelInterface>("Product", product, true)
            })
        })
    };

    /***
     * 根据id获取商品
     * @param id
     */
    @action.bound
    async getProductById(id: number) {
        this.imageSize = defaultObj;
        const {data} = await sendGetRequest<ProductResInterface<ProductModelExtraInfoInterface>>("main/getProductById", {id});
        runInAction(() => {
            this.productDetail = data;
        });
    }

    /***
     * 计算infoImage图片尺寸
     *
     */
    computedInfoImageSize() {
        const {imageUrl} = this.productDetail;
        runInAction(() => {

            Image.getSize(getAssetUrl(imageUrl), (width, height) => {
                const ratio = getImageSizeRatio(screenWidth, width);
                this.imageSize = {width: width * ratio, height: height * ratio};
            }, null);

        });

    }

    /***
     * 根据商品id获取评价
     * @param id
     */
    @action.bound
    async getProductCommentById(id: number) {
        const {data} = await sendGetRequest<ProductResInterface<ProductCommentInterface[]>>("main/getProductCommentById", {id});
        runInAction(() => {
            this.productComments = data;
        });
    }

    /***
     * 根据商品id获取规格
     * @param id
     */
    @action.bound
    async getProductSpecificationById(id: number) {
        const {data} = await sendGetRequest<ProductResInterface<ProductSpecificationInterface[]>>("main/getProductSpecificationById", {id});
        runInAction(() => {
            this.productSpecifications = data;
        });
    }

    /***
     * 获取用户和商品的关联个数限制
     * @param productId
     */
    @action.bound
    async getUserProductLimit(productId: number) {
        const {data} = await sendGetRequest<ProductResInterface<number>>("main/getUserProductLimit", {
            productId, userId: UserStoreInstance.user.id
        });
        runInAction(() => {
            this.buyMaxCount = data;
        });
        return data;
    }

    /***
     * 获取用户和商品的关联信息
     * @param productId
     */
    @action.bound
    async getUserProductRelation(productId: number) {
        const {data} = await sendGetRequest<ProductResInterface<UserProductRelationInterface>>("main/getUserProductRelation", {
            productId, userId: UserStoreInstance.user.id
        });
        runInAction(() => {
            this.userProductRelation = data;
        });
        return data;
    }

    /***
     * 收藏商品
     * @param productId
     * @param flag
     */
    @action.bound
    async collectProduct(productId: number,flag:boolean) {
        const {data} = await sendPostRequest<ProductResInterface<UserProductRelationInterface>>("main/collectProduct", {
            productId, userId: UserStoreInstance.user.id,flag:+flag
        });
        runInAction(() => {
            this.userProductRelation = data;
        });
        return data.collect;
    }

    /**
     * 计算是否还能购买商品
     */
    @computed get cantBuyAnyMore() {
        return this.buyMaxCount <= 0;
    }
}

export function getProductStoreInstance() {
    return new ProductStore();
}

const ProductStoreInstance = getProductStoreInstance();
export default ProductStoreInstance
